﻿using System;
using System.Windows;

using Microsoft.SharePoint.Client;

using SBPweb.RIA.Client.Controls.Base;

using SBPweb.PROvibe.Shared.Library.Components;

namespace SBPweb.PROvibe.Client.Modules.MOSS14Connector.Services
{

    public class Moss14ConnectorService : Library.Base.ServiceModelBase
    {

        #region Constructor logic

        public Moss14ConnectorService(IModule parentModule)
            : base(parentModule, "MOSS14Connector")
        {
            Uri uri = ExtendableApplication.Current.HostBaseUri;
            //TODO: get moss service url from configurationservice
            MossContext = new ClientContext(string.Format("{0}://{1}/", uri.Scheme, uri.DnsSafeHost));// ClientContext.Current;
            //MossContext = new ClientContext(string.Format("{0}://{1}/", uri.Scheme, "cerberus"));
        }

        #endregion

        #region Properties

        internal ClientContext MossContext
        {
            get;
            private set;
        }

        public bool IsAvailable
        {
            get
            {
                return MossContext != null;
            }
        }

        public bool IsInitialized
        {
            get;
            private set;
        }

        #endregion

        #region Events

        public event EventHandler Initialized;

        #endregion

        #region Methods

        public override void Initialize()
        {
            if (!IsAvailable)
            {
                return;
            }
            IsInitialized = false;

            MossContext.Load(MossContext.Site);
            MossContext.Load(MossContext.Web);
            MossContext.Load(MossContext.Web.Lists);
            MossContext.ExecuteQueryAsync(OnLoadSuccess, OnLoadFailure);  
        }

        private void OnLoadSuccess(object sender, ClientRequestSucceededEventArgs e)
        {
            IsInitialized = true;
            //string title = MossContext.Web.Title;
            //Application.Current.MainWindow.Dispatcher.BeginInvoke(() =>
            //{
            //    MessageBox.Show(string.Format("Sharepoint title: {0}", title));
            //});
            if (Initialized != null)
            {
                Initialized(this, e);
            }
        }

        private void OnLoadFailure(object sender, ClientRequestFailedEventArgs e)
        {
            if (e.Exception != null)
            {
                throw e.Exception;
            }
        }  

        #endregion

    }

}